package com.orkasgb.framework.springsecurity.usernamepassword;

import com.orkasgb.framework.springsecurity.CommonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 自定义失败处理器，用于处理登录失败的情况。
 * <p>
 * 仅将错误消息提供给前段，不受其他现有处理器的影响。
 */
@Component("orkasgbFailureHandler")
public class OrkasgbFailureHandler implements AuthenticationFailureHandler {

    /**
     * 处理登录失败的情况。
     *
     * @param request 请求
     * @param response 响应
     * @param exception 异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        System.out.println("认证失败" + exception.getMessage());
        response.getWriter().write(CommonResult.ofFailure("认证失败，" +  exception.getMessage()).toString());
    }
}
